package com.alan.api.config;

import com.alan.api.share.common.enums.ResponseCodeEnum;
import com.alan.api.share.dto.common.ResponseBase;
import com.alan.api.util.ResponseUtils;
import com.alan.server.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * Created by Alan on 17-10-13
 */
@Slf4j
@Component
public class ExceptionHandler implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception exception) {
        ModelAndView mav = new ModelAndView();
        // JSON格式返回
        if (exception instanceof ServiceException) {
            ServiceException ex = (ServiceException) exception;
            log.error("业务异常：{}",ex);
            ResponseBase responseBase = new ResponseBase();
            String code = ex.getErrorCode();
            responseBase.setCode(code);
            if(ResponseCodeEnum.INPUT_MUST_NOT_NULL.getCode().equals(code) && StringUtils.isNotEmpty(ex.getAttribute())){
                responseBase.setMsg(ex.getAttribute() + ":" + ex.getMessage());
            }else{
                responseBase.setMsg(ex.getMessage());
            }
            ResponseUtils.renderJson( response, JSONObject.toJSONString(responseBase) );
            return mav;
        }
        if(exception instanceof ConstraintViolationException){
            ConstraintViolationException ex = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>>  set = ex.getConstraintViolations();
            String msg = ResponseCodeEnum.INPUT_VALID_ERROR.getMsg();
            if(set.iterator().hasNext()){
                ConstraintViolation constraintViolation = set.iterator().next();
                msg = constraintViolation.getMessage();
            }
            ResponseBase responseBase = new ResponseBase();
            responseBase.setCode(ResponseCodeEnum.INPUT_VALID_ERROR.getCode());
            responseBase.setMsg(msg);
            log.error("参数异常：{}",JSONObject.toJSONString(responseBase));
            ResponseUtils.renderJson( response, JSONObject.toJSONString(responseBase) );
            return mav;
        }
        log.error("系统异常：{}",exception);
        ResponseBase responseBase = new ResponseBase();
        responseBase.setEnum(ResponseCodeEnum.UN_KNOWN);
        ResponseUtils.renderJson( response, JSONObject.toJSONString(responseBase) );
        return mav;
    }

}
